package com.sync.utils.framework.init;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import com.sync.utils.framework.entity.AppInfo;
import com.sync.utils.framework.redis.utils.RedisCache;
import com.sync.utils.project.demo.pojo.AppDto;
import com.sync.utils.project.demo.service.AppService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 * APP系统参数初始化加载
 *
 * @Author YWF
 * @Date 2021/3/21 21:48
 */
@Component
@Order(0)
public class ApplicationDataInit implements CommandLineRunner {

    private final static Logger logger = LoggerFactory.getLogger(ApplicationDataInit.class);

    @Value("${app.developer.cache_key}")
    private String appInfoCacheKey;

    @Autowired
    private RedisCache redisCache;

    @Autowired
    private AppService appService;

    @Override
    public void run(String... args) throws Exception {
        this.loadAppInfoForCache();
    }


    /**
     * 加载APP信息到缓存
     */
    private void loadAppInfoForCache(){
        final List<AppDto> list = appService.getAppList();;
        if (!CollectionUtil.isEmpty(list)){
            for (AppDto appDto : list) {
                AppInfo appInfo = BeanUtil.copyProperties(appDto,AppInfo.class);
                redisCache.hset(appInfoCacheKey,appDto.getAppKey(),appInfo);
            }
        }
        Map<String, Object> map = redisCache.hmget(appInfoCacheKey);
        logger.info("APP信息初始化完成，数据：{}",map);
    }
}